<?php

namespace App\Service;

use App\Model\ConfigNavModel;
use App\Model\OrderModel;
use App\Model\ShopCommentLabelModel;
use App\Model\ShopDiscountModel;
use App\Model\ShopGoodsCartModel;
use App\Model\ShopGoodsCateModel;
use App\Model\ShopGoodsCommentModel;
use App\Model\ShopGoodsItemModel;
use App\Model\ShopGoodsModel;
use App\Model\ShopModel;
use App\Model\ShopOrderItemModel;
use App\Model\ShopOrderModel;
use App\Model\ShopOwnNavModel;
use App\Model\ShopPostageTemplateModel;
use App\Model\UserModel;
use App\Utility\DataConversion;
use App\Utility\Payment;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

class ShopService extends BaseService
{
    /**
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getShopCate(): array
    {
        $cate = ShopGoodsCateModel::create()->where(['pid' => 0, 'is_deleted' => 0])->order('sort', 'DESC')->order('id', 'ASC')->all();
        $data = [];
        foreach ($cate as $item) {
            $data[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'icon' => $item['cover'],
                'image' => $item['image'],
                'cates' => $this->item_filter($item['id'])
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param int $nid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function item_filter(int $nid = 0): array
    {
        $tags = ShopGoodsCateModel::create()->order('sort', 'DESC')->order('id', 'ASC')->all(['pid' => $nid, 'is_deleted' => 0]);
        $data = [];
        if (!$tags) return $data;
        foreach ($tags as $k => $tag) {
            if ($tag['pid'] == $nid)
                $data[$k] = [
                    'id' => $tag['id'],
                    'name' => $tag['name'],
                    'icon' => $tag['cover'],
                    'image' => $tag['image'],
                    'cat' => $tag['id'],
                    'remark' => $tag['remark'],
                    'status' => $tag['status']
                ];
        }
        return $data;
    }

    /**
     * @param $nid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getShopCateS($nid): array
    {
        $data = $this->item_filter($nid);
        if (empty($data)) {
            return [
                'result' => false,
                'msg' => '暂无导航'
            ];
        }
        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $nid
     * @param $sort
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getGoodsList($nid, $sort, $limit, $page): array
    {
        $str = '%,' . $nid . ',%';
        $model = ShopGoodsModel::create()->where('cateids', $str, 'LIKE');
        switch ($sort) {
            case 1:
                $model->order('stock_sales', 'DESC');
                break;
            case 2:
                $model->order('good_comment', 'DESC');
                break;
            case 3:
                $model->order('price_selling', 'ASC');
                break;
            case 4:
                $model->order('price_selling', 'DESC');
                break;
            default:
                $model->order('sort', 'DESC');
                break;
        }
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无产品'
            ];
        }

        $data = [];

        foreach ($list as $item) {
            $marks = str_replace(',', ' · ', substr($item['marks'], 1, strlen($item['marks']) - 2));
            $data[] = [
                'id' => $item['id'],
                'sid' => $item['sid'],
                'name' => $item['name'],
                'marks' => $marks,
                'icon' => $item['cover'],
                'remark' => $item['remark'],
                'stock' => $item['stock_total'],
                'sales' => $item['stock_sales'],
                'good' => $item['good_comment'],
                'price' => $item['price_selling'],
                'oriPrice' => $item['price_market']
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];


    }

    /**
     * @param $gid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getGoodDetail($gid): array
    {
        $good = ShopGoodsModel::create()->getGoods(['id' => $gid]);
        if (!$good) {
            return [
                'result' => false,
                'msg' => '该产品已下架'
            ];
        }

        $good = $good->toArray();
        $good['banner'] = explode('|', $good['slider']);
        $good['marks'] = str_replace(',', ' · ', substr($good['marks'], 1, strlen($good['marks']) - 2));
        $good['discount'] = '';
        if ($good['discount_id'] != 0) {
            $discount = ShopDiscountModel::create()->getDiscount(['id' => $good['discount_id']]);
            if ($discount) {
                $good['discount'] = $discount->name;
            }
        }
        $good['truck'] = '';
        if ($good['truck_code'] != '') {
            $truck = ShopPostageTemplateModel::create()->getPostage(['code' => $good['truck_code']]);
            if ($truck) {
                $good['truck'] = $truck->name;
            }
        }
        $modelComments = ShopGoodsCommentModel::create()->where(['goods_code' => $good['code']]);
        $modelComments->limit(2)->withTotalCount();
        $comments = $modelComments->order('id', 'desc')->all(['is_deleted' => 0]);
        $result = $modelComments->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();
        $comments_data = [];
        foreach ($comments as $c) {
            $user = UserModel::create()->getUser(['id' => $c['uid']]);
            $comments_data[] = [
                'username' => $user->username,
                'uid' => $user->id,
                'avatar' => $user->avatar,
                'rate' => $c['rate'],
                'images' => json_decode($c['images'], true),
                'content' => $c['content'],
                'label' => '#' . str_replace(',', ' # # ', substr($c['label'], 1, strlen($c['label']) - 2)) . '#',
                'time' => date('Y-m-d H:i:s', $c['create_time'])
            ];
        }
        $commentsLabel = ['好评', '差评'];
        $labels = ShopCommentLabelModel::create()->where(['sid' => $good['sid'], 'is_deleted' => 0])->column('name');
        $commentsLabel = array_merge($commentsLabel, $labels);

        $comments_label = [];
        foreach ($commentsLabel as $v) {
            if ($v == '好评') {
                $num = $modelComments->where(['goods_code' => $good['code']])->where('rate', 4, '>=')->count();
            } elseif ($v == '差评') {
                $num = $modelComments->where(['goods_code' => $good['code']])->where('rate', 2, '<=')->count();
            } else {
                $num = $modelComments->where(['goods_code' => $good['code']])->where("label", '%,' . $v . ',%', 'LIKE')->count();
            }
            $comments_label[] = [
                'name' => $v,
                'badge' => [
                    'value' => $num
                ]
            ];
        }
        $good['comments'] = $comments_data;
        $good['comments_num'] = $total;
        $good['comments_label'] = $comments_label;
        $items = ShopGoodsItemModel::create()->where(['goods_code' => $good['code']])->all();
        $good['items'] = $items;
        $sku_list = [];
        foreach ($items as $e) {
            $arr1 = explode(";;", $e['goods_spec']);
            $spec = [];
            foreach ($arr1 as $a) {
                $aa = explode('::', $a);
                $spec[] = $aa[1];
            }
            $sku_list[] = [
                '_id' => $e['goods_sku'],
                'goods_id' => $good['code'],
                'goods_name' => $good['name'],
                'image' => $e['goods_image'],
                'price' => $e['price_selling'] * 100,
                'stock' => $e['stock_total'],
                'sku_name_arr' => $spec
            ];
        }
        $goodInfo = [
            '_id' => $good['code'],
            'name' => $good['name'],
            'goods_thumb' => $good['cover'],
            'spec_list' => json_decode($good['data_specs'], true),
            'sku_list' => $sku_list
        ];
        $good['shop'] = $this->shopDetail($good['sid']);

        $good['goodInfo'] = $goodInfo;
        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $good
        ];
    }

    /**
     * @param $sid
     * @return array|false
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    function shopDetail($sid)
    {
        $shop = ShopModel::create()->getShop(['id' => $sid]);
        if (!$shop) return false;
        $sales = ShopGoodsModel::create()->where(['sid' => $sid])->sum('stock_sales');
        $good = ShopGoodsModel::create()->where(['sid' => $sid])->sum('good_comment');
        $shop = $shop->toArray();
        $shop['sales'] = $sales;
        $shop['good'] = $good;
        unset($shop['password']);
        unset($shop['username']);
        unset($shop['login_ip']);
        $shop['goods'] = ShopGoodsModel::create()->where(['sid' => $sid, 'is_deleted' => 0])->order('sort', 'DESC')->limit(6)->all();
        return $shop;
    }

    /**
     * @param $sid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    function getShopDetail($sid): array
    {
        $shop = ShopModel::create()->getShop(['id' => $sid]);
        if (!$shop) {
            return [
                'result' => false,
                'msg' => '该店铺已关闭'
            ];
        }
        $sales = ShopGoodsModel::create()->where(['sid' => $sid])->sum('stock_sales');
        $good = ShopGoodsModel::create()->where(['sid' => $sid])->sum('good_comment');
        $shop = $shop->toArray();
        $shop['sales'] = $sales;
        $shop['good'] = $good;
        unset($shop['password']);
        unset($shop['username']);
        unset($shop['login_ip']);

        $nav = ShopOwnNavModel::create()->where(['sid' => $sid, 'pid' => 0])->all();
        $data = [];
        foreach ($nav as $item) {
            $data[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'icon' => $item['cover'],
                'cates' => $this->nav_filter($item['id'])
            ];
        }

        if (empty($data)) {
            $tabs = [['name' => '全部产品']];
        } else {
            $tabs = [['name' => '全部产品'], ['name' => '分类']];
        }
        $shop['tabs'] = $tabs;
        $shop['nav'] = $data;

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $shop
        ];
    }

    /**
     * @param int $nid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function nav_filter(int $nid = 0): array
    {
        $tags = ShopOwnNavModel::create()->order('sort', 'DESC')->order('id', 'ASC')->all(['pid' => $nid, 'is_deleted' => 0]);
        $data = [];
        if (!$tags) return $data;
        foreach ($tags as $k => $tag) {
            if ($tag['pid'] == $nid)
                $data[$k] = [
                    'id' => $tag['id'],
                    'name' => $tag['name'],
                    'icon' => $tag['cover'],
                    'cat' => $tag['id'],
                    'remark' => $tag['remark'],
                    'status' => $tag['status']
                ];
        }
        return $data;
    }

    /**
     * @param $sid
     * @param $sort
     * @param $limit
     * @param $page
     * @param $nid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getShopGoodsList($sid, $sort, $limit, $page, $nid): array
    {
        $model = ShopGoodsModel::create()->where(['sid' => $sid]);
        if ($nid != 0) {
            $str = '%,' . $nid . ',%';
            $model->where('s_cateids', $str, 'LIKE');
        }
        switch ($sort) {
            case 1:
                $model->order('stock_sales', 'DESC');
                break;
            case 2:
                $model->order('good_comment', 'DESC');
                break;
            case 3:
                $model->order('id', 'DESC');
                break;
            default:
                $model->order('sort', 'DESC');
                break;
        }
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无产品'
            ];
        }

        $data = [];

        foreach ($list as $item) {
            $marks = str_replace(',', ' · ', substr($item['marks'], 1, strlen($item['marks']) - 2));
            $data[] = [
                'id' => $item['id'],
                'sid' => $item['sid'],
                'name' => $item['name'],
                'marks' => $marks,
                'icon' => $item['cover'],
                'remark' => $item['remark'],
                'stock' => $item['stock_total'],
                'sales' => $item['stock_sales'],
                'good' => $item['good_comment'],
                'price' => $item['price_selling'],
                'oriPrice' => $item['price_market']
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $sku
     * @param $code
     * @param $num
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function addCart($uid, $sku, $code, $num): array
    {
        $goods = ShopGoodsItemModel::create()->getGoods(['goods_sku' => $sku, 'goods_code' => $code]);
        if (!$goods) {
            return [
                'result' => false,
                'msg' => '该商品已下架'
            ];
        }

        $good = ShopGoodsModel::create()->getGoods(['code' => $code]);
        if (!$good) {
            return [
                'result' => false,
                'msg' => '该商品已下架'
            ];
        }

        $par = [
            'uid' => $uid,
            'goods_sku' => $sku,
            'goods_code' => $code,
            'name' => $good->name,
            'goods_spec' => $goods->goods_spec,
            'goods_num' => $num,
            'goods_image' => $goods->goods_image ?? $good->cover
        ];

        $cart = ShopGoodsCartModel::create()->getGoods(['uid' => $uid, 'goods_sku' => $sku, 'goods_code' => $code]);
        if ($cart) {
            $num += $cart->goods_num;
            $p['goods_num'] = $num;
            $res = ShopGoodsCartModel::create()->update($p, ['uid' => $uid, 'goods_sku' => $sku, 'goods_code' => $code, 'is_deleted' => 0]);
        } else {
            $res = ShopGoodsCartModel::create()->addGoods($par);
        }

        if (!$res) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '添加成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getCart($uid): array
    {
        $carts = ShopGoodsCartModel::create()->where(['uid' => $uid, 'is_deleted' => 0])->all();
        if (empty($carts)) {
            return [
                'result' => false,
                'msg' => '暂无购物车数据'
            ];
        }

        $data = [];

        foreach ($carts as $cart) {
            $price = ShopGoodsItemModel::create()->field('price_selling,goods_code')->getGoods(['goods_sku' => $cart['goods_sku']]);
            $goods = ShopGoodsModel::create()->field('sid,id')->getGoods(['code' => $price->goods_code]);
            if ($price) {
                $data[] = [
                    'id' => $cart['id'],
                    'gid' => $goods->id,
                    'sid' => $goods->sid,
                    'img' => $cart['goods_image'],
                    'name' => $cart['name'],
                    'spec' => $cart['goods_spec'],
                    'price' => $price->price_selling ?? 0.00,
                    'number' => $cart['goods_num'],
                    'selected' => false,
                    'status' => 1
                ];
            } else {
                $data[] = [
                    'id' => $cart['id'],
                    'gid' => $goods->id,
                    'sid' => $goods->sid,
                    'img' => $cart['goods_image'],
                    'name' => $cart['name'],
                    'spec' => $cart['goods_spec'],
                    'price' => 0.00,
                    'number' => $cart['goods_num'],
                    'selected' => false,
                    'status' => -1
                ];
            }

        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function removeCart($uid, $id): array
    {
        $res = ShopGoodsCartModel::create()->update(['is_deleted' => 1], ['id' => $id, 'uid' => $uid]);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '操作成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @param $ids
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function clearCart($uid, $ids): array
    {
        $res = ShopGoodsCartModel::create()->where("id", $ids, 'IN')->update(['is_deleted' => 1], ['uid' => $uid]);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '操作成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @param $num
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function numChangeCart($uid, $id, $num): array
    {
        $cart = ShopGoodsCartModel::create()->getGoods(['uid' => $uid, 'id' => $id]);
        if (!$cart) {
            return [
                'result' => false,
                'msg' => '数据不存在'
            ];
        }

        $res = ShopGoodsCartModel::create()->update(['goods_num' => $num], ['uid' => $uid, 'id' => $id]);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '操作成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function recommendGoods($limit, $page): array
    {
        $model = new ShopGoodsModel();
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->order('stock_sales', 'DESC')->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无产品'
            ];
        }

        $data = [];

        foreach ($list as $item) {
            $marks = str_replace(',', ' · ', substr($item['marks'], 1, strlen($item['marks']) - 2));
            $data[] = [
                'id' => $item['id'],
                'sid' => $item['sid'],
                'name' => $item['name'],
                'marks' => $marks,
                'icon' => $item['cover'],
                'remark' => $item['remark'],
                'stock' => $item['stock_total'],
                'sales' => $item['stock_sales'],
                'good' => $item['good_comment'],
                'price' => $item['price_selling'],
                'oriPrice' => $item['price_market']
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    protected array $status = ['已取消', '预订单', '待支付', '支付中', '已支付', '已发货', '已完成'];

    /**
     * @param $uid
     * @param $status
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getOrderList($uid, $status, $limit, $page): array
    {
        $where = ['is_deleted' => 0, 'uuid' => $uid];
        switch ($status) {
            case 0:
                $where['status'] = 2;
                break;
            case 1:
                $where['status'] = 4;
                break;
            case 2:
                $where['status'] = 5;
                break;
            case 3:
                $where['status'] = 6;
                break;
            default:
                $where['is_deleted'] = 0;
                break;
        }

        $model = new ShopOrderModel();
        $model->where($where)->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->order('id', 'DESC')->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无订单'
            ];
        }

        $oids = array_column($list, 'order_no');
        $orderItem = ShopOrderItemModel::create()->where('order_no', $oids, 'IN')->all();

        $data = [];
        foreach ($list as $item) {
            $par = $item;
            $par['status_label'] = $this->status[$item['status']];
            $par['time'] = DataConversion::getInstance()->timeToDate($item['create_time']);

            $i = [];
            foreach ($orderItem as $value) {
                if ($value['order_no'] == $item['order_no']) {
                    $i[] = $value;
                }
            }
            $par['item'] = $i;
            $data[] = $par;
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $oid
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getOrderDetail($uid, $oid): array
    {
        $order = ShopOrderModel::create()->getOrder(['uuid' => $uid, 'id' => $oid]);
        if (!$order) {
            $order = ShopOrderModel::create()->getOrder(['uuid' => $uid, 'order_no' => $oid]);
            if (!$order) {
                return [
                    'result' => false,
                    'msg' => '该订单已失效'
                ];
            }
        }

        $order = $order->toArray();
        $orderItem = ShopOrderItemModel::create()->all(['order_no' => $order['order_no']]);
        foreach ($orderItem as $value) {
            $order['item'][] = $value;
        }
        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $order
        ];
    }

    /**
     * @param $uid
     * @param $goods
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function createOrder($uid, $goods): array
    {
        $sku = [];
        $items = [];
        foreach ($goods as $good) {
            $sku[] = $good['sku'];
            $items[$good['sku']] = $good['num'];
        }

        $goodsItem = ShopGoodsItemModel::create()->where("goods_sku", $sku, 'IN')->all();
        $order_no = DataConversion::getInstance()->get_order_no();
        $order = [
            'uuid' => $uid,
            'amount_real' => 0,
            'amount_total' => 0,
            'amount_goods' => 0,
            'order_no' => $order_no,
            'number_goods' => 0,
            'number_express' => count($goods),
            'status' => 2
        ];

        $order_item = [];

        foreach ($goodsItem as $item) {
            $g = ShopGoodsModel::create()->field('sid,id, name')->getGoods(['code' => $item['goods_code']]);
            $order_item[] = [
                'uuid' => $uid,
                'sid' => $g->sid,
                'order_no' => $order_no,
                'goods_sku' => $item['goods_sku'],
                'goods_code' => $item['goods_code'],
                'goods_spec' => $item['goods_spec'],
                'goods_name' => $g->name,
                'goods_cover' => $item['goods_image'],
                'price_selling' => $item['price_selling'],
                'price_market' => $item['price_market'],
                'total_selling' => $item['price_selling'] * $items[$item['goods_sku']],
                'total_market' => $item['price_market'] * $items[$item['goods_sku']],
                'stock_sales' => $items[$item['goods_sku']]
            ];

            $order['amount_real'] += ($item['price_selling'] * $items[$item['goods_sku']]);
            $order['amount_total'] += ($item['price_selling'] * $items[$item['goods_sku']]);
            $order['amount_goods'] += ($item['price_selling'] * $items[$item['goods_sku']]);
            $order['number_goods'] += $items[$item['goods_sku']];
        }
        try {
            // 开启事务
            DbManager::getInstance()->startTransaction();
            $res = ShopOrderItemModel::create()->addAll($order_item);
            $oRes = ShopOrderModel::create()->addOrder($order);

            // 提交事务
            DbManager::getInstance()->commit();
            $status = true;
        } catch (Throwable $e) {
            // 回滚事务
            DbManager::getInstance()->rollback();
            $status = false;
        }

        if (!$status) {
            return [
                'result' => false,
                'msg' => '下单失败'
            ];
        }

        return [
            'result' => true,
            'msg' => '下单成功',
            'data' => $order_no
        ];
    }

    /**
     * @param $uid
     * @param $order_no
     * @param $truck_type
     * @param $order_remark
     * @param $aid
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function confirmOrder($uid, $order_no, $truck_type, $order_remark, $aid, $ip): array
    {
        if ($truck_type == 0) {
            $par = ['truck_type' => $truck_type, 'order_remark' => $order_remark, 'status' => 3];
        } else {
            $par = ['truck_type' => $truck_type, 'order_remark' => $order_remark, 'status' => 3, 'aid' => $aid];
        }
        $res = ShopOrderModel::create()->where(['order_no' => $order_no, 'uuid' => $uid])->update($par);

        if (!$res) {
            return [
                'result' => false,
                'msg' => '确认失败'
            ];
        }

        $order = ShopOrderModel::create()->getOrder(['order_no' => $order_no]);
        if (!$order) {
            return [
                'result' => false,
                'msg' => '该订单不存在'
            ];
        }

        $appid = ConfigService::getInstance()->getSys("mxappid", 'wepay');
        $mxappid = ConfigService::getInstance()->getSys("mxminiappid", 'wepay');
        $mchid = ConfigService::getInstance()->getSys("mchid", 'wepay');
        $password = ConfigService::getInstance()->getSys("mxpassword", 'wepay');
        $cert = ConfigService::getInstance()->getSys("cert", 'wepay');
        $key = ConfigService::getInstance()->getSys("key", 'wepay');
        $notifyUrl = ConfigService::getInstance()->getSys("wenotify_url", 'wepay');
        $user = UserModel::create()->getUser(['id' => $uid]);
        if (!$user || $user->we_code == '') {
            return [
                'result' => false,
                'msg' => 'openidNotFound'
            ];
        }

        $res = Payment::getInstance()->mxWepay($appid, $mxappid, $mchid, $password, $cert, $key, $user->we_code, $order_no, $order->amount_total * 100, $order_remark, $notifyUrl, $ip);
        $result = $res->toArray();
        $parOrder = [
            'uid' => $uid,
            'type' => 0,
            'rid' => $order->id,
            'order_no' => $order_no,
            'amount_real' => $order->amount_total,
            'order_remark' => '【商城购物】' . $order_no . '支付' . $order->amount_total . '元',
            'status' => 3
        ];

        $resOrder = OrderModel::create()->addOrder($parOrder);
        if (!$resOrder) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '成功',
            'data' => $result ?? 'success'
        ];
    }

    /**
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getHomeShopNav(): array
    {
        $shop = ConfigNavModel::create()->getConfig(['method' => 'shop']);
        if (!$shop) {
            return [
                'result' => false,
                'msg' => '暂未开启商城'
            ];
        }

        $nav = ShopGoodsCateModel::create()->where("pid", '0', "<>")->limit(3)->order("sort", "DESC")->all();
        if (empty($nav)) {
            return [
                'result' => false,
                'msg' => '暂无数据'
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $nav
        ];
    }
}